package com.loveshare.imgshow.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * ClassName: ImgShowUtil 
 * @Description: 图片展示工具类
 * @author 爱分享
 * @date 2017年12月20日
 */
public class ImgShowUtil {

	
	private static final String A_HREF = "href=\"(.*?)\"";
	/**
	 * 根据URL获取HTML代码 作者:王锋 时间:2017年12月7日
	 */
	public static String getHtml(String url) {
		StringBuffer sb = new StringBuffer();
		try {
			// 使用java.net.URL
			URL url1 = new URL(url);
			// 打开链接
			URLConnection connection = url1.openConnection();
			// 获取输入流
			InputStream in = connection.getInputStream();
			// 流的包装
			InputStreamReader isr = new InputStreamReader(in);
			BufferedReader br = new BufferedReader(isr);
			String line;
			// 整行读取
			while ((line = br.readLine()) != null) {
				// 添加到StringBuffer中
				sb.append(line, 0, line.length());
				// 添加换行符
				sb.append('\n');
			}
			// 关闭各种流，先声明的后关闭
			br.close();
			isr.close();
			in.close();
			return sb.toString();
		} catch (Exception e) {
			System.out.println("错误啦···");
			System.out.println(url);
		}
		return sb.toString();
	}

	/**
	 * 获取html里面的img src属性
	 * 
	 * @param htmlStr
	 * @return
	 */
	public static List<String> getImgStr(String htmlStr) {
		List<String> pics = new ArrayList<String>();
		String img = "";
		Pattern pImage;
		Matcher mImage;
		//图片链接地址
		// String regExImg = "<img.*src=(.*?)[^>]*?>"; 
		String regExImg = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
		pImage = Pattern.compile(regExImg, Pattern.CASE_INSENSITIVE);
		mImage = pImage.matcher(htmlStr);
		String regExSrc = "src\\s*=\\s*\"?(.*?)(\"|>|\\s+)";
		while (mImage.find()) {
			// 得到<img />数据
			img = mImage.group();
			// 匹配<img>中的src数据
			
			Matcher m = Pattern.compile(regExSrc).matcher(img);
			while (m.find()) {
				if (m.group(1).indexOf(".jpg") != -1) {
					pics.add(m.group(1));
				}
			}
		}
		return pics;
	}
	
	/**
	 * 获取网页所有a标签
	 * @return
	 */
	public static List<String> getHrefHmlts(String htmlStr){
		List<String>  al=new ArrayList<String>();
        String regex="<a.*?/a>";
        Pattern pt=Pattern.compile(regex);
        Matcher mt=pt.matcher(htmlStr);
        while(mt.find()){
        	String s3 = "href=\"(.*?)\"";
            Pattern pt3=Pattern.compile(s3);
            Matcher mt3=pt3.matcher(mt.group());
            while(mt3.find())
            {
                //System.out.println("网址："+mt3.group().replaceAll("href=|>",""));
                String u=mt3.group().replaceAll("href=|>","");
                al.add(u);
            }
        }
		return al;
	}
	/**
	 * 从网络Url中下载文件
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
		URL url = new URL(urlStr);  
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
                //设置超时间为3秒
		conn.setConnectTimeout(3*1000);
		//防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		//得到输入流
		InputStream inputStream = conn.getInputStream();  
		//获取自己数组
		byte[] getData = readInputStream(inputStream);    

		//文件保存位置
		File saveDir = new File(savePath);
		if(!saveDir.exists()){
			saveDir.mkdir();
		}
		File file = new File(saveDir+File.separator+fileName);    
		FileOutputStream fos = new FileOutputStream(file);     
		fos.write(getData); 
		if(fos!=null){
			fos.close();  
		}
		if(inputStream!=null){
			inputStream.close();
		}
		System.out.println("info:"+url+" download success"); 

	}
	/**
	 * 从输入流中获取字节数组
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
		byte[] buffer = new byte[1024];  
		int len = 0;  
		ByteArrayOutputStream bos = new ByteArrayOutputStream();  
		while((len = inputStream.read(buffer)) != -1) {  
			bos.write(buffer, 0, len);  
		}  
		bos.close();  
		return bos.toByteArray();  
	}  
	
	public static void main(String[] args) {
		String urlHtml=getHtml("http://www.win4000.com/meitu.html");
		//System.out.println(urlHtml);
		List<String> hrefs=getHrefHmlts(urlHtml);
		List<String> imgs=getImgStr(urlHtml);
		for (String string : imgs) {
			System.out.println(string);
		}
		for (String string : hrefs) {
			System.out.println(string);
		}
		//System.out.println(hrefs);
		//System.out.println(imgs);
		/*for (String s : hrefs) {
			if(s.indexOf("topic")!=-1){
				//System.out.println("======"+s);
				//拿到图片详情的大图
				String ImgUrlHtml=getHtml(s.replace("\"", ""));
				List<String> imgs=getImgStr(ImgUrlHtml);
				for (String img : imgs) {
					if(img.indexOf("sinaimg.cn")!=-1&&img.indexOf("https")!=-1){
						System.out.println("最终图片地址："+img);
					}
				}
			}
		}*/
		
		//http://www.win4000.com/meinv171373.html
	}
}
